package com.sloth.bear.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sloth.bear.constant.ResultCode;
import com.sloth.bear.dto.entity.Doc;
import com.sloth.bear.dto.entity.Namespace;
import com.sloth.bear.dto.request.NamespaceRequest;
import com.sloth.bear.dto.vo.NamespaceVo;
import com.sloth.bear.exception.BusinessException;
import com.sloth.bear.mapper.NameSpaceMapper;
import com.sloth.bear.service.DocService;
import com.sloth.bear.service.NamespaceService;
import com.sloth.bear.util.AssertUtils;
import com.sloth.bear.util.BaseHelper;
import com.sloth.bear.util.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 命名空间服务实现类
 */
@RequiredArgsConstructor
@Service
public class NameSpaceServiceImpl extends ServiceImpl<NameSpaceMapper, Namespace> implements NamespaceService {

    private final DocService docService;

    @Override
    public List<NamespaceVo> listNameSpace() {
        List<Namespace> spaces = list(Wrappers.<Namespace>lambdaQuery()
                .eq(UserContext.getUserId() == null, Namespace::getPermission, 1)
                .orderByAsc(Namespace::getSortNo)
                .orderByDesc(Namespace::getCreatedTime));

        return spaces.stream()
                .map(this::convertToVo)
                .collect(Collectors.toList());
    }

    @Override
    public NamespaceVo getSpaceById(Long id) {
        Namespace space = getById(id);
        if (space == null) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "命名空间不存在");
        }
        return convertToVo(space);
    }

    @Override
    public void createSpace(NamespaceRequest request) {
        Namespace nameSpace = BaseHelper.r2t(request, Namespace.class);
        boolean result = save(nameSpace);
        AssertUtils.isTrue(result, "创建命名空间失败");
    }

    @Override
    public NamespaceVo updateSpace(Long id, NamespaceRequest request) {
        Namespace existSpace = getById(id);
        if (existSpace == null) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "命名空间不存在");
        }

        existSpace.setName(request.getName());
        existSpace.setDescription(request.getDescription());
        existSpace.setSortNo(request.getSortNo() != null ? request.getSortNo() : 0);

        boolean result = updateById(existSpace);
        AssertUtils.isTrue(result, "更新命名空间失败");
        return convertToVo(existSpace);
    }

    @Override
    public void deleteSpace(Long id) {
        if (id == null) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "命名空间ID不能为空");
        }

        Namespace existSpace = getById(id);
        if (existSpace == null) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "命名空间不存在");
        }

        // 检查是否还有文档关联此空间
        long count = docService.count(Wrappers.<Doc>lambdaQuery().eq(Doc::getNamespaceId, id));
        AssertUtils.isTrue(count == 0, "该空间下还有文档，无法删除");

        boolean result = removeById(id);
        AssertUtils.isTrue(result, "删除命名空间失败");
    }

    private NamespaceVo convertToVo(Namespace space) {
        NamespaceVo vo = BaseHelper.r2t(space, NamespaceVo.class);
        // 统计文档数量
//        vo.setDocumentCount(docService.count(Wrappers.<Doc>lambdaQuery().eq(Doc::getNamespaceId, space.getId())));
        return vo;
    }
}